import { Card, Input, App } from 'antd';
import { RcFile } from 'antd/es/upload';
import React, { useState, useEffect, useRef, useMemo } from 'react';
import { useLocation } from 'react-router-dom';

import orchestrationService from '@/api/services/orchestrationService';
import { AppCreateTypeEnum, defaultImgList } from '@/common/app/constants';
import AppTagSelect from '@/components/AppTagSelect';
import { CustomFormLabel, PrefixStyleLabel } from '@/components/eai-design';
import { DEFAULT_IMAGES } from '@/components/work-modal/components/ImageDisplay';
import LogoSelector, {
  agentLogos,
  fusionLogos,
  workflowLogos,
} from '@/components/work-modal/components/LogoSelector';
import { SceneImageType } from '@/components/work-modal/components/SceneImageSelector';
import { MongoImageTypeEnum } from '@/pages/chat/tools/constants';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { compressImgFileAndUpload } from '@/types/app/api';
import { StorageEnum } from '@/types/enum';
import { getItem } from '@/utils/storage';

import type { UploadProps } from 'antd';

const BasicInfo: React.FC<{ isPreview?: boolean; isWorkflow?: boolean; className?: string }> = ({
  isPreview = false,
  isWorkflow = false,
  className = '',
}) => {
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';
  const isInitialMount = useRef(true);
  const { message } = App.useApp();
  const {
    special_app_lable,
    configurations,
    updateConfiguration,
    appLogoList,
    sceneImageList,
    setSceneImage,
    setAppLogo,
    setAppDescription,
    setAppName,
    setTag,
    tag,
    appName,
    appDescription,
    appLogo,
    sceneImage,
    setAppLogoList,
    setSceneImageList,
    appDetail,
  } = useOrchestrationStore();

  const defaultLogo = useMemo(() => {
    if (appDetail?.appType === AppCreateTypeEnum.workflow) {
      return workflowLogos[0].id;
    }
    if (appDetail?.appType === AppCreateTypeEnum.fusion) {
      return fusionLogos[0].id;
    }
    if (appDetail?.appType === AppCreateTypeEnum.agent) {
      return agentLogos[0].id;
    }
    return 'default';
  }, [appDetail?.appType]);

  // 从 configurations 中获取应用名称、描述、logo和场景图片
  const appNameConfig =
    (configurations.find((config) => config.name === 'app_name')?.default_value as string) ||
    appName ||
    '';
  const tagConfig = appDetail?.tag || null;

  const appDescriptionConfig =
    (configurations.find((config) => config.name === 'app_description')?.default_value as string) ||
    appDescription ||
    '';
  const appLogoConfig =
    (configurations.find((config) => config.name === 'app_logo')?.default_value as string) ||
    appLogo ||
    defaultLogo;

  const sceneImageConfig =
    (configurations.find((config) => config.name === 'scene_image')?.default_value as string) ||
    sceneImage ||
    '';

  const [logoOption, setLogoOption] = useState<string>(appLogoConfig);
  const [sceneImageOption, setSceneImageOption] = useState<'match' | 'custom'>(
    // (sceneImageConfig === appLogoConfig) ? 'match' : 'custom',
    !sceneImageConfig ? 'match' : 'custom',
  );
  const [selectedSceneImage, setSelectedSceneImage] = useState<string | null>(sceneImageConfig);
  const [logoLoading, setLogoLoading] = useState(false);
  const [sceneImageLoading, setSceneImageLoading] = useState(false);
  const [customLogos, setCustomLogos] = useState<string[]>([]);
  const [customSceneImages, setCustomSceneImages] = useState<string[]>([]);
  const isTianGongManager = Boolean(
    (getItem(StorageEnum.User) as any)?.is_TianGong === 'true' ||
      (getItem(StorageEnum.User) as any)?.is_TianGong === true,
  );

  useEffect(() => {
    setTag(appDetail.tag);
  }, [appDetail.tag]);

  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }

    orchestrationService.updateAppImage(appId, {
      logo: customLogos.filter(Boolean),
      scene: customSceneImages.filter(Boolean),
    });
    setAppLogoList(customLogos);
    setSceneImageList(customSceneImages);
  }, [customLogos, customSceneImages]);

  useEffect(() => {
    const fetchAppImage = async () => {
      const appImage = await orchestrationService.getAppImage(appId);
      const newCustomLogos = [
        ...new Set([
          ...appImage.logo,
          ...(defaultImgList.includes(appLogoConfig) ? [] : [appLogoConfig]),
        ]),
      ];
      const newCustomSceneImages = [
        ...new Set([
          ...appImage.scene,
          ...(defaultImgList.includes(sceneImageConfig) || !sceneImageConfig
            ? []
            : [sceneImageConfig]),
        ]),
      ];

      setCustomLogos(newCustomLogos);
      setCustomSceneImages(newCustomSceneImages);
    };
    fetchAppImage();
    return () => {
      setCustomLogos([]);
      setCustomSceneImages([]);
    };
  }, []);

  // 预设场景图片
  const sceneImages: SceneImageType[] = [
    {
      id: 'edu',
      type: 'default',
      name: '校园',
    },
    {
      id: 'ent',
      type: 'enterprise',
      name: '企业',
    },
    {
      id: 'med',
      type: 'medical',
      name: '医疗',
    },
  ];

  const sceneImagesSpecial: SceneImageType[] = [
    {
      id: 'aiaa',
      type: 'AIAA',
      name: '招生助手',
    },
  ];

  const defaultSceneCustom = useMemo(() => {
    if (customSceneImages?.length > 0 && customSceneImages?.[0]) {
      return customSceneImages?.[0];
    }
    if (special_app_lable && special_app_lable == '招生助手') {
      return 'aiaa';
    }
    return 'edu';
  }, [special_app_lable, customSceneImages]);

  useEffect(() => {
    if (sceneImageOption === 'match') {
      updateConfiguration('scene_image', '');
      setSelectedSceneImage('');
    } else if (!sceneImageConfig) {
      updateConfiguration('scene_image', defaultSceneCustom);
      setSelectedSceneImage(defaultSceneCustom);
    } else {
      updateConfiguration('scene_image', sceneImageConfig);
      setSelectedSceneImage(sceneImageConfig);
    }
    // if (sceneImageOption === 'match') {
    //   updateConfiguration('scene_image', "");
    //   setSelectedSceneImage("");
    // } else {
    //   if (!sceneImageConfig || sceneImageConfig === appLogoConfig) {
    //     updateConfiguration('scene_image', sceneImages?.[0].id);
    //     setSelectedSceneImage(sceneImages?.[0].id);
    //   } else {
    //     updateConfiguration('scene_image', sceneImageConfig);
    //     setSelectedSceneImage(sceneImageConfig);
    //   }
    // }
  }, [sceneImageOption, appLogoConfig]);

  // 初始化场景图片选择状态
  useEffect(() => {
    if (!sceneImageConfig || appLogoConfig === sceneImageConfig) {
      setSceneImageOption('match');
      setSelectedSceneImage('');
    } else {
      const matchingImage = sceneImages.find((img) => img.id === sceneImageConfig);
      if (matchingImage) {
        setSceneImageOption('custom');
        setSelectedSceneImage(matchingImage.id);
      } else if (sceneImageConfig !== defaultLogo) {
        setSceneImageOption('custom');
        setSelectedSceneImage(sceneImageConfig);
      }
    }
  }, [appLogoConfig, sceneImageConfig]);

  useEffect(() => {
    setSceneImage(selectedSceneImage || '');
    // setSceneImage(selectedSceneImage && special_app_lable == "招生助手" ? 'aiaa' : 'edu');
  }, [selectedSceneImage]);

  useEffect(() => {}, []);

  const handleAppNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    updateConfiguration('app_name', e.target.value);
    setAppName(e.target.value);
  };

  const handleAppTagChange = (tag: string) => {
    updateConfiguration('tag', tag);
    setTag(tag);
  };

  const handleAppDescriptionChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    updateConfiguration('app_description', e.target.value);
    setAppDescription(e.target.value);
  };

  const handleLogoSelect = (url: string) => {
    setLogoOption(url);
    updateConfiguration('app_logo', url);
    setAppLogo(url);
  };

  const handleLogoDelete = (logoUrl: string) => {
    setCustomLogos((prev) => prev.filter((url) => url !== logoUrl));
    if (appLogoConfig === logoUrl) {
      updateConfiguration('app_logo', defaultLogo);
      setLogoOption(defaultLogo);
      setAppLogo(defaultLogo);
    }
  };

  const handleSceneImageOptionChange = (option: 'match' | 'custom') => {
    setSceneImageOption(option);
    if (option === 'match') {
      updateConfiguration('scene_image', '');
      setSelectedSceneImage('');
    } else {
      updateConfiguration('scene_image', defaultSceneCustom);
      setSelectedSceneImage(defaultSceneCustom);
    }
  };

  const handleSceneImageSelect = (imageId: string) => {
    setSelectedSceneImage(imageId);
    updateConfiguration('scene_image', imageId);
  };

  const handleSceneImageDelete = (imageUrl: string) => {
    setCustomSceneImages((prev) => prev.filter((url) => url !== imageUrl));
    if (sceneImageConfig === imageUrl) {
      updateConfiguration('scene_image', 'edu');
      setSelectedSceneImage('edu');
    }
  };

  const beforeUpload = (file: RcFile) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB！');
      return false;
    }
    return true;
  };

  const logoBeforeUpload = (file: RcFile) => {
    if (!beforeUpload(file)) {
      return false;
    }
    if (customLogos.filter((logo) => !Object.keys(DEFAULT_IMAGES).includes(logo)).length >= 5) {
      message.warning('最多只能上传5张图片，请先删除已有图片。');
      return false;
    }
    return true;
  };

  const sceneImageBeforeUpload = (file: RcFile) => {
    if (!beforeUpload(file)) {
      return false;
    }
    if (
      customSceneImages.filter((logo) => !Object.keys(DEFAULT_IMAGES).includes(logo)).length >= 5
    ) {
      message.warning('最多只能上传5张图片，请先删除已有图片。');
      return false;
    }
    return true;
  };

  const handleLogoUpload = async (file: File) => {
    setLogoLoading(true);
    try {
      const src = await compressImgFileAndUpload({
        type: MongoImageTypeEnum.appAvatar,
        file,
        maxW: 300,
        maxH: 300,
      });
      const url = new URL(src);
      const path = url.pathname.replace('//', '/');
      setCustomLogos((prev) => [path, ...prev]);
      updateConfiguration('app_logo', path);
      setAppLogo(path);
      setLogoOption(path);
      message.success('Logo上传成功');
    } catch (error) {
      message.error('Logo上传失败');
    } finally {
      setLogoLoading(false);
    }
  };

  const handleSceneImageUpload = async (file: File) => {
    setSceneImageLoading(true);
    try {
      const src = await compressImgFileAndUpload({
        type: MongoImageTypeEnum.appAvatar,
        file,
        maxW: 300,
        maxH: 300,
      });
      const url = new URL(src);
      const path = url.pathname.replace('//', '/');
      setCustomSceneImages((prev) => [path, ...prev]);
      updateConfiguration('scene_image', path);
      setSelectedSceneImage(path);
      message.success('场景图片上传成功');
    } catch (error) {
      message.error('场景图片上传失败');
    } finally {
      setSceneImageLoading(false);
    }
  };

  const logoUploadProps: UploadProps = {
    name: 'file',
    showUploadList: false,
    beforeUpload: logoBeforeUpload,
    customRequest: ({ file }) => handleLogoUpload(file as File),
    disabled: isPreview,
  };

  const sceneImageUploadProps: UploadProps = {
    name: 'file',
    showUploadList: false,
    beforeUpload: sceneImageBeforeUpload,
    customRequest: ({ file }) => handleSceneImageUpload(file as File),
    disabled: isPreview,
  };

  return (
    <Card
      className={`orch-card-body mb-4 h-full overflow-auto [-ms-overflow-style:none] [scrollbar-width:none] ${className} ${
        isPreview ? 'pointer-events-none' : ''
      }`}
      style={{ background: isWorkflow ? '#fff' : '', border: isWorkflow ? 'none' : '' }}
    >
      <div className="space-y-4">
        {/* 应用名称 */}
        <div>
          <CustomFormLabel
            className="mb-2 mt-2"
            prefix
            required
            description="设置智能体应用的正式名称"
          >
            应用名称
          </CustomFormLabel>

          <div className="relative">
            <Input
              className="w-full focus:border-[#D9D9D9] focus:outline-none"
              value={appNameConfig}
              onChange={handleAppNameChange}
              placeholder="为您的应用命名"
              maxLength={20}
              // disabled={isPreview || isTianGongManager}
              disabled={isPreview}
              style={{ paddingRight: '60px' }}
            />
            <div className="pointer-events-none absolute bottom-1 right-2 text-[14px] text-[#A5A9BB]">
              {appNameConfig.length || 0} / 20
            </div>
          </div>
        </div>

        {/* 应用描述（可选） */}
        <div>
          <CustomFormLabel
            className="mb-2"
            prefix
            description="在此填写关于该智能体应用功能的详细介绍和说明"
          >
            描述
          </CustomFormLabel>

          <div className="relative text-[14px] text-[#424242]">
            <Input.TextArea
              className="w-full resize-none rounded-lg border p-2 [-ms-overflow-style:none] [scrollbar-width:none] focus:border-[#D9D9D9] focus:outline-none"
              maxLength={200}
              placeholder="输入应用的描述，以便他人更好了解应用情况"
              value={appDescriptionConfig}
              onChange={handleAppDescriptionChange}
              style={{ borderColor: '#D9D9D9', paddingBottom: '24px' }}
              autoSize={{ minRows: 4, maxRows: 6 }}
              disabled={isPreview}
            />
            <div className="pointer-events-none absolute bottom-2 right-2 text-[14px] text-[#A5A9BB]">
              {appDescriptionConfig.length || 0} / 200
            </div>
          </div>
        </div>
        {/* 应用标签 */}
        <AppTagSelect className="w-full" value={tagConfig} needAdd tagChange={handleAppTagChange} />

        {/* 应用Logo */}
        <div className="flex">
          <PrefixStyleLabel className="mt-1" />
          <LogoSelector
            appType={appDetail?.appType}
            uploadedLogoUrl={appLogoConfig}
            selectedLogoId={appLogoConfig}
            customLogos={customLogos}
            loading={logoLoading}
            onSelect={handleLogoSelect}
            onDelete={handleLogoDelete}
            uploadProps={logoUploadProps}
          />
        </div>

        {/* 场景图片 */}
        {/* <SceneImageSelector
          sceneImages={special_app_lable && special_app_lable == "招生助手" ? [...sceneImagesSpecial, ...sceneImages] : sceneImages}
          uploadedImageUrl={sceneImageConfig}
          selectedImage={selectedSceneImage}
          customSceneImages={customSceneImages}
          sceneImageOption={sceneImageOption}
          sceneImageLoading={sceneImageLoading}
          onOptionChange={handleSceneImageOptionChange}
          onImageSelect={handleSceneImageSelect}
          onImageDelete={handleSceneImageDelete}
          uploadProps={sceneImageUploadProps}
        /> */}
      </div>
    </Card>
  );
};

export default BasicInfo;
